package com.exercise.ThreadSynchronization.SynchronizedCode;

public class SyncInstanceMethodCounter {
    private int count = 0;

    //同步实例方法，锁对象是this
    public synchronized void increment() {
        count++;
        System.out.println("Count: " + count + " by " + Thread.currentThread().getName());
    }

    public int getCount() {
        return count;
    }

    public static void main(String[] args) throws InterruptedException {
       //创建共享的计数器对象
        SyncInstanceMethodCounter counter = new SyncInstanceMethodCounter();
        //定义任务：每个线程调用 1000 次 increment
        Runnable task = () ->{
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        };

        //创建两个线程
        Thread thread1 = new Thread(task, "Thread-1");
        Thread thread2 = new Thread(task, "Thread-2");

        //启动线程
        thread1.start();
        thread2.start();

        //等待线程结束
        thread1.join();
        thread2.join();

        // 输出最终计数
        System.out.println("Final count: " + counter.getCount()); // 预期输出：2000
    }
}
